package com.game.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;

public class DBConnection {

	private static int maxConnectNum = 20;

	private java.sql.Connection conn[] = new Connection[maxConnectNum];

	private static ArrayList<Connection> connectPool = new ArrayList<Connection>();

	private static int flag = 0;

	public DBConnection() {
		if (flag == 0) {
			init();
		}
	}

	private Connection getConnectionFromDatabase() {
		Connection trueConn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			String url = "jdbc:mysql://localhost:3306/rpgdb?user=root&password=&characterEncoding=UTF8";
			trueConn = DriverManager.getConnection(url);
		} catch (Exception ex) {
			System.out.println("数据连接出错了:" + ex.toString());
		}
		return trueConn;
	}

	// 这里建立所有的连接;
	private void init() {
		for (int i = 0; i < maxConnectNum; i++) {
			conn[i] = getConnectionFromDatabase();
			connectPool.add(i, conn[i]);
		}
		flag = 1;
	}

	// 从连接池中取得一个可用的连接
	public synchronized Connection getConnection() {
		Connection conn = null;
		if (connectPool.size() == 0) {
			try {
				java.lang.Thread.sleep(1000);
				getConnection();
			} catch (InterruptedException ex) {
				System.out.println("连接全部用光,这里sleep出错了.");
			}
		} else {
			conn = (Connection) connectPool.remove(0);
		}

		return conn;
	}

	// 提供给外部程序调用,不用的连接放回连接池当中...
	public synchronized boolean release(Connection conn) {
		return connectPool.add(conn);
	}
}
